package cn.px.hro.company_agreement.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import cn.px.common.annotation.DataScope;
import cn.px.common.exception.ServiceException;
import cn.px.common.utils.StringUtils;
import cn.px.crm.customer.domain.CrmCustomer;
import cn.px.crm.customer.service.ICrmCustomerService;
import cn.px.hro.common.enums.HroEnum;
import cn.px.hro.company.service.IHroCompanyService;
import cn.px.hro.company_agreement_charge_unit.domain.HroCompanyAgreementChargeUnit;
import cn.px.hro.company_agreement_charge_unit.service.IHroCompanyAgreementChargeUnitService;
import cn.px.hro.company_agreement_file.domain.HroCompanyAgreementFile;
import cn.px.hro.company_agreement_file.service.IHroCompanyAgreementFileService;
import cn.px.system.service.IHroAreaService;
import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.px.common.annotation.Log;
import cn.px.common.core.controller.BaseController;
import cn.px.common.core.domain.AjaxResult;
import cn.px.common.enums.BusinessType;
import cn.px.hro.company_agreement.domain.HroCompanyAgreement;
import cn.px.hro.company_agreement.service.IHroCompanyAgreementService;
import cn.px.common.utils.poi.ExcelUtil;
import cn.px.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 平台与客户企业合同Controller
 *
 * @author ruoyi
 * @date 2023-06-10
 */
@RestController
@RequestMapping("/companyAgreement/companyAgreement")
public class HroCompanyAgreementController extends BaseController {
    @Autowired
    private IHroCompanyAgreementService hroCompanyAgreementService;
    @Autowired
    private IHroAreaService hroAreaService;
    @Autowired
    private IHroCompanyAgreementFileService agreementFileService;
    @Autowired
    private IHroCompanyService companyService;
    @Autowired
    private IHroCompanyAgreementChargeUnitService chargeUnitService;
    @Autowired
    private ICrmCustomerService crmCustomerService;

    /**
     * 查询平台与客户企业合同列表
     */
    @PreAuthorize("@ss.hasPermi('companyAgreement:companyAgreement:list')")
    @GetMapping("/list")
    @DataScope(deptAlias = "g", userAlias = "u")
    public TableDataInfo list(HroCompanyAgreement hroCompanyAgreement) {
        startPage();
        List<HroCompanyAgreement> list = hroCompanyAgreementService.selectHroCompanyAgreementList(hroCompanyAgreement);
        Iterator<HroCompanyAgreement> iterator = list.iterator();
        while (iterator.hasNext()) {
            HroCompanyAgreement next = iterator.next();
            StringBuilder address = new StringBuilder();
            String actualConstructionProvinceName = next.getActualConstructionProvinceName();
            String actualConstructionCityName = next.getActualConstructionCityName();
            if (StringUtils.isNotEmpty(actualConstructionProvinceName)){
                address.append(actualConstructionProvinceName);
            }
            if (StringUtils.isNotEmpty(actualConstructionCityName)){
                address.append(actualConstructionCityName);
            }
            next.setActualConstructionAddress(address.toString());
        }
        return getDataTable(list);
    }

    /**
     * 导出平台与客户企业合同列表
     */
    @PreAuthorize("@ss.hasPermi('companyAgreement:companyAgreement:export')")
    @Log(title = "平台与客户企业合同", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @DataScope(deptAlias = "g", userAlias = "u")
    public void export( HroCompanyAgreement hroCompanyAgreement, HttpServletResponse response) {
        List<HroCompanyAgreement> list = hroCompanyAgreementService.selectHroCompanyAgreementList(hroCompanyAgreement);
        ExcelUtil<HroCompanyAgreement> util = new ExcelUtil<HroCompanyAgreement>(HroCompanyAgreement.class);
        util.exportExcel(response, list, "平台与客户企业合同数据");
    }

    /**
     * 获取平台与客户企业合同详细信息
     */
    @PreAuthorize("@ss.hasPermi('companyAgreement:companyAgreement:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        HroCompanyAgreement hroCompanyAgreement = hroCompanyAgreementService.selectHroCompanyAgreementById(id);
        if (hroCompanyAgreement != null) {
            HroCompanyAgreementFile hroCompanyAgreementFile = new HroCompanyAgreementFile();
            hroCompanyAgreementFile.setComAgreementId(id);
            List<HroCompanyAgreementFile> hroCompanyAgreementFiles = agreementFileService.selectHroCompanyAgreementFileList(hroCompanyAgreementFile);
            if (CollectionUtils.isNotEmpty(hroCompanyAgreementFiles)) {
                hroCompanyAgreement.setAgreementFileList(hroCompanyAgreementFiles);
                List<String> fileUrlStrList = new ArrayList<>();
                for (HroCompanyAgreementFile item : hroCompanyAgreementFiles) {
                    if (StringUtils.isNotBlank(item.getUrl())) {
                        fileUrlStrList.add(item.getUrl());
                    }
                }
                hroCompanyAgreement.setFileUrlStrList(fileUrlStrList);
            }

            //
            HroCompanyAgreementChargeUnit hroCompanyAgreementChargeUnit = new HroCompanyAgreementChargeUnit();
            hroCompanyAgreementChargeUnit.setComAgreementId(id);
            List<HroCompanyAgreementChargeUnit> hroCompanyAgreementChargeUnits = chargeUnitService.selectHroCompanyAgreementChargeUnitList(hroCompanyAgreementChargeUnit);
            hroCompanyAgreement.setChargeUnits(hroCompanyAgreementChargeUnits);
        }
        return success(hroCompanyAgreement);
    }

    /**
     * 新增平台与客户企业合同
     */
    @PreAuthorize("@ss.hasPermi('companyAgreement:companyAgreement:add')")
    @Log(title = "平台与客户企业合同", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HroCompanyAgreement hroCompanyAgreement) {
        if(StringUtils.isNotBlank(hroCompanyAgreement.getServerMoneyEquation())){
            if(CollectionUtils.isNotEmpty(hroCompanyAgreement.getChargeUnits())){
                String finalServerMoneyEquation = hroCompanyAgreement.getServerMoneyEquation();
                for(HroCompanyAgreementChargeUnit item : hroCompanyAgreement.getChargeUnits()){
                    if(StringUtils.isNotBlank(item.getKey())){
                        finalServerMoneyEquation = finalServerMoneyEquation.replaceAll(getKeyData(item.getKey(),"key"),getKeyData(item.getKey(),"id"));
                    }
                }
                hroCompanyAgreement.setFinalServerMoneyEquation(finalServerMoneyEquation);
            }
        }
        if(StringUtils.isNotBlank(hroCompanyAgreement.getSalaryEquation())){
            if(CollectionUtils.isNotEmpty(hroCompanyAgreement.getChargeUnits())){
                String finalSalaryEquation = hroCompanyAgreement.getSalaryEquation();
                for(HroCompanyAgreementChargeUnit item : hroCompanyAgreement.getChargeUnits()){
                    if(StringUtils.isNotBlank(item.getKey())){
                        finalSalaryEquation = finalSalaryEquation.replaceAll(getKeyData(item.getKey(),"key"),getKeyData(item.getKey(),"id"));
                    }
                }
                hroCompanyAgreement.setFinalSalaryEquation(finalSalaryEquation);
            }
        }

        int i = hroCompanyAgreementService.insertHroCompanyAgreement(hroCompanyAgreement);
        if (i > 0) {
            //添加签约主体
//            Long signMainId = hroCompanyAgreement.getSignMainId();
//            Long companyId = hroCompanyAgreement.getCompanyId();
//            HroCompany hroCompany = new HroCompany();
//            hroCompany.setSignMainId(signMainId);
//            hroCompany.setId(companyId);
//            companyService.updateHroCompany(hroCompany);
            Long id = hroCompanyAgreement.getId();
            Long companyId = hroCompanyAgreement.getCompanyId();
            //新增合同附件
            if (CollectionUtils.isNotEmpty(hroCompanyAgreement.getAgreementFileList())) {
                for (HroCompanyAgreementFile item : hroCompanyAgreement.getAgreementFileList()) {
//                    HroCompanyAgreementFile agreementFile = new HroCompanyAgreementFile();
//                    agreementFile.setComAgreementId(hroCompanyAgreement.getId());
//                    agreementFile.setUrl(str);
                    item.setComAgreementId(id);
                    agreementFileService.insertHroCompanyAgreementFile(item);
                }
            }

            String chargeUnitCategory = hroCompanyAgreement.getChargeUnitCategory();
            List<HroCompanyAgreementChargeUnit> chargeUnits = hroCompanyAgreement.getChargeUnits();
            if (CollectionUtils.isNotEmpty(chargeUnits) && StringUtils.isNotBlank(chargeUnitCategory)){
                for(HroCompanyAgreementChargeUnit chargeUnit : chargeUnits){
                    chargeUnit.setType(chargeUnitCategory);
                    chargeUnit.setComAgreementId(id);
                }
                chargeUnitService.insertComAgreementChargeUnitBatch(chargeUnits);
            }
            // 修改crm客户状态
            CrmCustomer crmCustomer = new CrmCustomer();
            crmCustomer.setHroCompanyId(companyId);
            List<CrmCustomer> crmCustomers = crmCustomerService.selectCrmCustomerList(crmCustomer);
            if (!crmCustomers.isEmpty()){
                CrmCustomer crmCustomerSelect = crmCustomers.get(0);
                Long idCustomer = crmCustomerSelect.getId();
                CrmCustomer customer = new CrmCustomer();
                customer.setId(idCustomer);
                customer.setStatus("8");
                crmCustomerService.updateCrmCustomer(customer);
            }

        }
        return i > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 修改平台与客户企业合同
     */
    @PreAuthorize("@ss.hasPermi('companyAgreement:companyAgreement:edit')")
    @Log(title = "平台与客户企业合同", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HroCompanyAgreement hroCompanyAgreement) {
        if(StringUtils.isNotBlank(hroCompanyAgreement.getServerMoneyEquation())){
            if(CollectionUtils.isNotEmpty(hroCompanyAgreement.getChargeUnits())){
                String finalServerMoneyEquation = hroCompanyAgreement.getServerMoneyEquation();
                for(HroCompanyAgreementChargeUnit item : hroCompanyAgreement.getChargeUnits()){
                    if(StringUtils.isNotBlank(item.getKey())){
                        finalServerMoneyEquation = finalServerMoneyEquation.replaceAll(getKeyData(item.getKey(),"key"),getKeyData(item.getKey(),"id"));
                    }
                }
                hroCompanyAgreement.setFinalServerMoneyEquation(finalServerMoneyEquation);
            }
        }
        if(StringUtils.isNotBlank(hroCompanyAgreement.getSalaryEquation())){
            if(CollectionUtils.isNotEmpty(hroCompanyAgreement.getChargeUnits())){
                String finalSalaryEquation = hroCompanyAgreement.getSalaryEquation();
                for(HroCompanyAgreementChargeUnit item : hroCompanyAgreement.getChargeUnits()){
                    if(StringUtils.isNotBlank(item.getKey())){
                        finalSalaryEquation = finalSalaryEquation.replaceAll(getKeyData(item.getKey(),"key"),getKeyData(item.getKey(),"id"));
                    }
                }
                hroCompanyAgreement.setFinalSalaryEquation(finalSalaryEquation);
            }
        }
        int i = hroCompanyAgreementService.updateHroCompanyAgreement(hroCompanyAgreement);
        if (i > 0) {
            //修改签约主体
//            Long signMainId = hroCompanyAgreement.getSignMainId();
//            Long companyId = hroCompanyAgreement.getCompanyId();
//            HroCompany hroCompany = new HroCompany();
//            hroCompany.setSignMainId(signMainId);
//            hroCompany.setId(companyId);
//            companyService.updateHroCompany(hroCompany);
            //调整合同附件
            if (CollectionUtils.isNotEmpty(hroCompanyAgreement.getAgreementFileList())) {
                agreementFileService.deleteHroCompanyAgreementFileByAgreementIds(new Long[]{hroCompanyAgreement.getId()});
                for (HroCompanyAgreementFile item : hroCompanyAgreement.getAgreementFileList()) {
//                    HroCompanyAgreementFile agreementFile = new HroCompanyAgreementFile();
//                    agreementFile.setComAgreementId(hroCompanyAgreement.getId());
//                    agreementFile.setUrl(str);
                    item.setComAgreementId(hroCompanyAgreement.getId());
                    agreementFileService.insertHroCompanyAgreementFile(item);
                }
            }
            //处理项目表数据
            if(CollectionUtils.isNotEmpty(hroCompanyAgreement.getChargeUnits())){
                //删除
                chargeUnitService.deleteChargeUnitByAgreementIds(new Long[]{hroCompanyAgreement.getId()} );
                String chargeUnitCategory = hroCompanyAgreement.getChargeUnitCategory();
                List<HroCompanyAgreementChargeUnit> chargeUnits = hroCompanyAgreement.getChargeUnits();
                for(HroCompanyAgreementChargeUnit item : chargeUnits){
                    item.setType(chargeUnitCategory);
                    item.setComAgreementId(hroCompanyAgreement.getId());
                }
                chargeUnitService.insertComAgreementChargeUnitBatch(chargeUnits);
            }
        }
        return toAjax(i);
    }

    /**
     * 删除平台与客户企业合同
     */
    @PreAuthorize("@ss.hasPermi('companyAgreement:companyAgreement:remove')")
    @Log(title = "平台与客户企业合同", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        int i = hroCompanyAgreementService.deleteHroCompanyAgreementByIds(ids);
        if ( i > 0 ){
            agreementFileService.deleteHroCompanyAgreementFileByAgreementIds(ids);
            chargeUnitService.deleteChargeUnitByAgreementIds(ids);
//            List<HroCompanyAgreement> companyAgreementList = hroCompanyAgreementService.selectAgreementListByIds(ids);
//            if ( companyAgreementList.size() > 0){
//                Long[] companyIds= companyAgreementList.stream().map(HroCompanyAgreement::getCompanyId).toArray(Long[]::new);
//                //解约签约主体
//                companyService.abandonSignMainById(companyIds);
//            }
        }
        return toAjax(i);
    }

    /**
     * 获取客户合同全列表
     *
     * @param hroCompanyAgreement
     * @return
     */
    @GetMapping("/listAllCompanyAgreement")
    public List<HroCompanyAgreement> listAllCompanyAgreement(HroCompanyAgreement hroCompanyAgreement) {
        hroCompanyAgreement.setStatus(HroEnum.EFFECTIVE_STATUS_0.getCode());
        return hroCompanyAgreementService.selectHroCompanyAgreementList(hroCompanyAgreement);
    }

    /**
     * 导入客户合同
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "平台与客户企业合同", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('companyAgreement:companyAgreement:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) {
        String message;
        try {

            ExcelUtil<HroCompanyAgreement> util = new ExcelUtil<HroCompanyAgreement>(HroCompanyAgreement.class);
            List<HroCompanyAgreement> companyAgreementList = util.importExcel(file.getInputStream());
            String operName = getUsername();
            message = hroCompanyAgreementService.importCompanyAgreement(companyAgreementList, updateSupport, operName);
        } catch ( NullPointerException e){
            message = "导入失败！请检查文件数据格式是否符合模板！";
            e.printStackTrace();
        }catch ( ServiceException e){
            message = e.getMessage();
            e.printStackTrace();
        }
        catch ( Exception e) {
            message = "导入失败！请联系管理员！";
            e.printStackTrace();
        }
        return success(message);
    }

    /**
     * 下载模板
     *
     * @param response
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<HroCompanyAgreement> util = new ExcelUtil<HroCompanyAgreement>(HroCompanyAgreement.class);
        util.importTemplateExcel(response, "客户合同数据");
    }

    //获取JSON中某个key值
    private String getKeyData(String json,String key){
        JSONObject parse = JSONObject.parse(json);
        String str = parse.get(key).toString();
        return str;
    }

}
